package com.jm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jm.reggie.common.CustomException;
import com.jm.reggie.common.R;
import com.jm.reggie.entity.User;
import com.jm.reggie.service.UserService;
import com.jm.reggie.utils.RandomUtil;
import com.jm.reggie.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 用户管理
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 发送短信验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机4位二维码
            String code = RandomUtil.getFourBitRandom();
            log.info("code:{}", code);

            //调用容联云短信API发送消息
            //SMSUtils.send(phone, code);

            //将二维码存到session
            session.setAttribute("code", code);

            return R.success("短信发送成功");
        }

        return R.error("短信发送失败");
    }

    /**
     * 用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号
        String phone = (String) map.get("phone");

        //获取验证码
        String code = (String) map.get("code");

        //从session获取保存到验证码
        String sessionCode = (String) session.getAttribute("code");

        //进行验证码比对（页面提交的验证码和session中保存到验证码比对）
        if (sessionCode != null && code.equals(sessionCode)) {
            //如果比对成功，说明登录成功
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);
            User user = userService.getOne(wrapper);
            //判断当前手机号是否为新用户，如果为新用户则自动完成注册
            if (user==null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //将userId存到session
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("登陆失败");
    }
}
